from src.db.mssql import MSSQL
from src.db.mysql import MySql
from src.utils.loghelper import logHelper
from src.utils.config_utils import DataConfigParser

dbConfig_token = "dbConfig"
dbConfig_dbserver_token = "dbUserMySQL"


class DBProvider():
    __instance = None

    __dbSql = None

    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
            return cls.__instance
        else:
            # 上一次创建的对象的引用
            return cls.__instance

    def initial(self, host, user, pwd, db_name):

        try:
            db_server = DataConfigParser().get_data_configuration(dbConfig_token, dbConfig_dbserver_token)

            if db_server == "1":
                self.__dbSql = MySql(host, user, pwd, db_name)
            else:
                self.__dbSql = MSSQL(host, user, pwd, db_name)

        except Exception as e:
            logHelper.error(e)

    def create_tables(self, create_table_str):
        if self.__dbSql is not None and create_table_str is not None:
            for create_table in create_table_str:
                self.__dbSql.exec_non_query(create_table)

    def insert(self, sql):
        try:
            self.__dbSql.exec_non_query(sql)
        except Exception as e:
            logHelper.error(e)

    def execute(self, sql):
        try:
            self.__dbSql.exec_query(sql)
        except Exception as e:
            logHelper.error(e)